<template>
  <basic-dialog
    width="60%"
    :visible="visible"
    :showFooter="false"
    :handleClose="handleCancel"
  >
    <div>
      <div class="page-container" v-loading="pageLoading">
        <template v-if="isUnify()">
          <UnifyBatchSetData
            ref="areaSetRef"
            @update-city="updateBatchCityByUnify"
            @update-ratio="updateBatchRatioByUnify"
          />
        </template>
        <template v-else>
          <AreaBatchSetData ref="areaSetRef" @confirm="updateBatchSetInfoByArea" />
        </template>
        <SelectSupplyCities @update="updateSalesListBySupplyCities" />
        <CitiesTable
          :data-source.sync="TableInfo.list"
          @update-info="updateTableInfo"
        />
      </div>
      <div class="footer-wrap" slot="ft">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </div>
  </basic-dialog>
</template>
<script>
import { mapState, mapGetters, mapMutations } from 'vuex';
import BasicDialog from '@/components/BasicDialog';
import AreaBatchSetData from './AreaBatchSetData.vue';
import UnifyBatchSetData from './UnifyBatchSetData';
import SelectSupplyCities from './SelectSupplyCities';
import CitiesTable from './CitiesTable.vue';
import { TableInfo, getCityNamesByPurchaseIneligibleRatio } from '@/utils/getUtils';
import {
  getInitSalesCitiesList,
  getTemplateCityInfo,
} from './utils';
import {
  getSupplyProvinceBySupplyNoService,
  getSupplyCityByAreaCodesService,
  getPriceRatioByAreaCodeService
} from '@/api/commodity/common';
export default {
  components: {
    BasicDialog,
    AreaBatchSetData,
    UnifyBatchSetData,
    SelectSupplyCities,
    CitiesTable
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
  },
  data () {
    return {
      pageLoading: false,
      TableInfo: new TableInfo(),
    }
  },
  computed: {
    ...mapState('commonComps/referCitiesUpdate', [
      'checkedSupplyCityCodes', // 选中的供货城市code集合
    ]),
    ...mapGetters('commonComps/referCitiesUpdate', [
      'isSupply', // 是否供货
      'isUnify', // 是否统一进价
    ]),
  },
  watch: {
    visible: {
      handler (newVal) {
        if (newVal) {
          this.setReferRelList()
        }
      },
      immediate: true
    }
  },
  methods: {
    ...mapMutations('commonComps/referCitiesUpdate', [
      'UPDATE_REFER_CITIES_OPTIONS', // 更新参照城市下拉列表
      'UPDATE_SUPPLY_CITIES_OPTIONS', // 更新供货城市集合
      'UPDATE_CHECKED_SUPPLY_CITY_CODES', // 更新已勾选的供货城市编码集合
    ]),
    // 确定
    handleConfirm () {
      if (this.validateResults()) return
      this.$emit('getReferList', this.TableInfo.list)
      this.handleCancel()
    },
    handleCancel () {
      this.$refs.areaSetRef.clear()
      this.$emit('update:visible', false)
    },
    // 获取供货城市复选列表数据
    async getSupplyCitiesList () {
      const data = { supplierCode: this.$attrs?.supplierCode }
      const res = await getSupplyProvinceBySupplyNoService(data)
      return res?.retData ?? []
    },
    // 获取销售城市表格列表数据
    async getSalesCitiesList () {
      const data = { areaCode: this.$attrs?.areaCodes }
      const res = await getSupplyCityByAreaCodesService(data)
      return res?.retData ?? []
    },
    // 设置参照相关集合
    async setReferRelList () {
      try {
        this.pageLoading = true
        const [supplyReult, salesResult] = await Promise.allSettled([this.getSupplyCitiesList(), this.getSalesCitiesList()])
        this.pageLoading = false
        const supplyCitiesList = supplyReult.status == 'fulfilled' ? supplyReult.value : []
        const supplyCityCodes = supplyReult.value.map(item => item.cityCode) // 供货城市编码集合
        const salesCitiesList = salesResult.status == 'fulfilled' ? getInitSalesCitiesList(salesResult.value, this.isUnify(), supplyCityCodes) : []
        const referCitiesOptions = salesCitiesList.map(item => ({
          value: item.saleCityUuid,
          label: item.saleCityName
        }))
        this.TableInfo.setList(salesCitiesList)
        this.UPDATE_SUPPLY_CITIES_OPTIONS(supplyCitiesList)
        this.UPDATE_CHECKED_SUPPLY_CITY_CODES(supplyCityCodes)
        this.UPDATE_REFER_CITIES_OPTIONS(referCitiesOptions)
      } catch (err) {
        this.pageLoading = false
      }
    },
    // 更新TableInfo
    updateTableInfo (infoVo) {
      this.TableInfo = infoVo
    },
    // 供货城市变更更新销售城市表格数据
    updateSalesListBySupplyCities () {
      const updateSalesList = this.TableInfo.list.map(item => ({
        ...item,
        ...getTemplateCityInfo(item, this.checkedSupplyCityCodes)
      }))
      this.TableInfo.setList(updateSalesList)
    },
    // 统一进价批量设置参照城市
    updateBatchCityByUnify (infoData) {
      const { templateCityUuid, templateCityName } = infoData ?? {}
      const updateList = this.TableInfo.list.map(item => ({
        ...item, templateCityUuid, templateCityName
      }))
      this.TableInfo.setList(updateList)
    },
    // 统一进价批量设置成本价比例
    updateBatchRatioByUnify (costPriceRatio) {
      if (this.TableInfo.isNullSelection()) return this.$message.warning('请勾选列表后操作')
      if (!costPriceRatio) return this.$message.warning('批量设置成本价比例不能都为空')
      const updateList = this.TableInfo.list.map(item => ({
        ...item, costPriceRatio
      }))
      this.TableInfo.setList(updateList)
    },
    // 批量设置数据变更更新销售城市表格数据
    updateBatchSetInfoByArea (infoData) {
      const { costPriceRatio, templateCityUuid, templateCityName } = infoData ?? {}
      if (this.TableInfo.isNullSelection()) return this.$message.warning('请勾选列表后操作')
      if (!costPriceRatio && !templateCityUuid) return this.$message.warning('批量设置成本价比例和参照城市不能都为空')
      if (!costPriceRatio && templateCityUuid) return this.batchUpdateCostRatioCityList({ templateCityUuid, templateCityName })
      const updateList = this.TableInfo.list.map(item => ({
        ...item, templateCityUuid, templateCityName, costPriceRatio
      }))
      this.TableInfo.setList(updateList)
    },
    // 获取更新成本价格比例后的数据集合
    async batchUpdateCostRatioCityList ({ templateCityUuid, templateCityName }) {
      // 获取更新后的表格数据方法
      const getUpdateList = list => this.TableInfo.list.map(item => {
        const cityInfo = (list ?? []).find(el => el.saleCityUuid == item.saleCityUuid)
        if (cityInfo) return {
          ...item,
          templateCityUuid,
          templateCityName,
          costPriceRatio: cityInfo?.costPriceRatio,
          buyPriceRatio: cityInfo?.buyPriceRatio ?? 1 // 进价比例默认为1
        }
        return {
          ...item,
          templateCityUuid,
          templateCityName,
          costPriceRatio: 1,
          buyPriceRatio: 1
        }
      })
      // 销售城市不供货的设置参照城市的时候需要获取成本价比率
      const data = this.TableInfo.selection
        .filter(item => !this.isSupply(item))
        .map(item => ({ saleCityUuid: item.saleCityUuid, templateCityUuid }))
      if (data.length == 0) return this.TableInfo.setList(getUpdateList())
      const res = await getPriceRatioByAreaCodeService(data, this.TableInfo.setLoading)
      this.TableInfo.setList(getUpdateList(res?.retData))
    },
    // 确定操作校验
    validateResults () {
       // 有城市没有设置参照城市
      const hasInCompleteReferCities = this.TableInfo.list.some(item => !item.templateCityUuid)
      if (hasInCompleteReferCities) return this.$message.warning('请填写完整参照城市')
      // 有相互参照的城市
      const hasReferCityByCrossReference = this.TableInfo.list.some(
        row => row.saleCityUuid != row.templateCityUuid &&
        this.TableInfo.list.find(item => row.saleCityUuid === item.templateCityUuid)
      )
      if (hasReferCityByCrossReference) return this.$message.warning('参照城市之间不能互相参照')
      // 有价格比例不在0.6-5之间的城市
      const warnMsgs = getCityNamesByPurchaseIneligibleRatio(this.TableInfo.list)
      if (warnMsgs) return this.$message.warning(`${warnMsgs}：进价比例和成本价比例均需在0.6-5之间`)
    },
  }
}
</script>
<style lang="less" scoped>
.page-container {
  div:not(:first-child) {
    margin-top: 15px;
  }
}
/deep/ .el-dialog__header {
  border-bottom: none
}
.footer-wrap {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}
</style>
